package com.example.socket.socket.bio.server.client;

import java.io.*;
import java.net.Socket;

public class ChartClient {

    private final String DEFULT_SERVER_HOST="127.0.0.1";

    private final int DEFUT_SERVER_PORT=8888;

    private final String QUIT="quit";

    private Socket socket;

    private BufferedReader reader;

    private BufferedWriter writer;
    //发送消息给服务器
    public void send(String msg) throws IOException {
        if(!socket.isOutputShutdown()){
            writer.write(msg+"\n");
            writer.flush();
        }
    }
    //从服务器接受消息
    public String receive() throws IOException {
        String msg=null;
        if(!socket.isInputShutdown()){
            msg=reader.readLine();
        }
        return msg;
    }
    //检查用户是否准备推出
    public boolean readyToQuit(String msg){
        return QUIT.equals(msg);
    }

    public void close(){
        if(writer!=null){
            try {
                System.out.println("关闭sockt");
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void start(){
        //创建sockt
        try {
            //创建socket
            socket=new Socket(DEFULT_SERVER_HOST,DEFUT_SERVER_PORT);
            //创建IO流
            reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));

            writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            //处理用户输入
            new Thread(new UserInputHandler(this)).start();
            //读取服务器转发的消息
            String  msg=null;
            while ((msg=receive())!=null){
                System.out.println(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            close();
        }
    }

    public static void main(String[] args) {
        ChartClient chartClient=new ChartClient();
        chartClient.start();
    }
}
